package cn.jdemo.juc.servlet;

import cn.jdemo.juc.anno.MyController;
import cn.jdemo.juc.anno.MyRequestMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * Description : 并发问题不予考虑
 * ProjectName parent_will
 * Created by 张刘伟 on 2018/8/16 9:39.
 * Version 1.0
 */
public class MyDispatcherServlet extends HttpServlet {
	
    private Properties properties = new Properties();

    // 指定扫描包下,所有类路径
    private List<String> classNames = new ArrayList<String>();

    // beanId --> 对应的实例
    private Map<String, Object> ioc = new HashMap<String, Object>();

    // 映射路径 --> 具体的方法体上
    private Map<String, Method> handlerMapping = new HashMap<String, Method>();

    // 映射路径 --> 对应的实例
    private Map<String, Object> controllerMap  =new HashMap<String, Object>();


    /**
     * **********************************初始化***************************************************
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件 （ServletConfig:代表当前Servlet在web.xml中的配置信息）
        this.doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.初始化所有相关联的类,扫描用户设定的包下面所有的类
        doScanner(properties.getProperty("scanPackage"));

        //3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写
        doInstance();

        //4.初始化HandlerMapping(将url和method对应上)
        initHandlerMapping();
    }


    /**
     * **********************************加载***************************************************
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //处理请求
            doDispatch(req,resp);
        } catch (Exception e) {
            resp.getWriter().write("500!! Server Exception");
        }
    }

    /**
     * **********************************加载：实操***************************************************
     */
    // 处理请求
    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if(handlerMapping.isEmpty()){
            return;
        }
        /*request.getRequestURL() 返回全路径
        request.getRequestURI() 返回除去host（域名或者ip）部分的路径
        request.getContextPath() 返回工程名部分，如果工程映射为/，此处返回则为空
        request.getServletPath() 返回除去host和工程名部分的路径*/
        String url =req.getRequestURI();
        String contextPath = req.getContextPath();
        //拼接url并把多个/替换成一个
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        if(!this.handlerMapping.containsKey(url)){
            resp.setStatus(200);
            resp.getWriter().write("404 NOT FOUND!");
            return;
        }

        Method method =this.handlerMapping.get(url);

        // 获取参数注解
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();

        // 获取方法的参数列表
        Class<?>[] parameterTypes = method.getParameterTypes();

        // 获取请求的参数
        Map<String, String[]> parameterMap = req.getParameterMap();

        //保存参数值
        Object [] paramValues= new Object[parameterTypes.length];

        //方法的参数列表
        for (int i = 0; i<parameterTypes.length; i++){
            //根据参数名称，做某些处理
            String requestParam = parameterTypes[i].getSimpleName();
            if (requestParam.equals("HttpServletRequest")){
                //参数类型已明确，这边强转类型
                paramValues[i]=req;
                continue;
            }
            if (requestParam.equals("HttpServletResponse")){
                paramValues[i]=resp;
                continue;
            }

            // TODO:待完善: error
            if(requestParam.equals("String")){
                for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
                    String[] paramValue = param.getValue();
                    String value = Arrays.toString(paramValue).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
                    paramValues[i] = value;
                }
            }
        }

        //利用反射机制来调用
        try {
            method.invoke(this.controllerMap.get(url), paramValues);//obj是method所对应的实例 在ioc容器中
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * **********************************初始化：实操***************************************************
     */
    //4.初始化HandlerMapping(将url和method对应上)
    private void initHandlerMapping() {
        if(ioc.isEmpty()){
            return;
        }
        try {
            Set<Map.Entry<String, Object>> entries = ioc.entrySet();

            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                Object obj = entry.getValue();
                Class<?> objClass = obj.getClass();

                // 再次校验
                if(!objClass.isAnnotationPresent(MyController.class)){
                    continue;
                }

                // 类上的映射路径
                String baseUrl = "";
                if(objClass.isAnnotationPresent(MyRequestMapping.class)){
                    if (objClass.isAnnotationPresent(MyRequestMapping.class)){
                        baseUrl = objClass.getAnnotation(MyRequestMapping.class).value();
                    }
                }

                Method[] methods = objClass.getMethods();
                for (Method method : methods) {
                    // 方法上没有 映射
                    if (!method.isAnnotationPresent(MyRequestMapping.class)){
                        continue;
                    }
                    String url_part = method.getAnnotation(MyRequestMapping.class).value();
                    String url = (baseUrl+"/"+url_part).replaceAll("/+", "/");

                    //这里应该放置实例和method
                    handlerMapping.put(url,method);
                    // TODO: objClass.newInstance()创建新的实例
                    // controllerMap.put(url,objClass.newInstance());
                    controllerMap.put(url,obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写
    private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }
        for (String className : classNames) {
            try {
                //把类搞出来,反射来实例化(只有加@MyController需要实例化)
                Class<?> clazz =Class.forName(className);
                if(clazz.isAnnotationPresent(MyController.class)){
                    ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance());
                }else{
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }


    // 2.初始化所有相关联的类,扫描用户设定的包下面所有的类
    private void doScanner(String packageName) {
        //把所有的.替换成/
        URL url  =this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.", "/"));
        File dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            if(file.isDirectory()){
                //递归读取包
                doScanner(packageName+"."+file.getName());
            }else{
                String className =packageName +"." +file.getName().replace(".class", "");
                classNames.add(className);
            }
        }

    }

    // 1.加载配置文件
    private void doLoadConfig(String location) {
        //把web.xml中的contextConfigLocation对应value值的文件加载到留里面
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
        try {
            //用Properties文件加载文件里的内容
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关流
            if(null!=resourceAsStream){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 首字母转小写
    private String toLowerFirstWord(String simpleName) {
        char[] charArray = simpleName.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);
    }

}
